from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json

mcp = FastMCP("Jetty MCP Server")

"""
Jetty MCP Server

面向软件：jetty（Java Web 服务器和 Servlet 容器）

MCP tools 列表：
1. jetty_service_restart - 重启 jetty 服务
   参数：无
   返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}

2. jetty_service_reload - 重载 jetty 服务
   参数：无
   返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}
"""

@mcp.tool()
def jetty_service_restart() -> dict:
    """
    重启 jetty 服务
    
    用途：执行 systemctl restart jetty.service 命令来重启 jetty 服务
    参数：无
    返回：统一的 JSON 结构，包含命令执行结果
    """
    command = ["systemctl", "restart", "jetty.service"]
    
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

@mcp.tool()
def jetty_service_reload() -> dict:
    """
    重载 jetty 服务
    
    用途：执行 systemctl reload jetty.service 命令来重载 jetty 服务
    参数：无
    返回：统一的 JSON 结构，包含命令执行结果
    """
    command = ["systemctl", "reload", "jetty.service"]
    
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()